package cn.smart.epic.core.shiro;

import cn.smart.epic.common.persistence.model.User;
import cn.smart.epic.core.shiro.factory.IShiro;
import cn.smart.epic.core.shiro.factory.ShiroFactroy;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Auther Z.B
 * @date 2017/10/11 16:08
 * @Email 2545375@qq.com
 * @Description 请输入你的描述
 * @since 1.0
 */

public class ShiroDbRealm extends AuthorizingRealm {

    /**
     * 权限认证
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        IShiro shiroFactory = ShiroFactroy.me();
        ShiroUser shiroUser =(ShiroUser) principalCollection.getPrimaryPrincipal();
        List<Integer> roleList = shiroUser.getRoleList();

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        roleList.stream().forEach(role ->{
            List<String> premissions = shiroFactory.findPermissionByRoleId(role);
            if (premissions != null) {
              info.addStringPermissions(premissions.stream().filter(StringUtils::isNotEmpty).distinct()
                      .collect(Collectors.toSet()));
            }
            Set<String> roleNameSet = new HashSet<>();
            roleNameSet.add(shiroFactory.findRoleNameByRoleId(role));
            info.addRoles(roleNameSet);
        });
        return info;
    }

    /**
     * 登陆认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        IShiro shiroFactory= ShiroFactroy.me();
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        User user = shiroFactory.user(token.getUsername());
        ShiroUser shiroUser = shiroFactory.shiroUser(user);
        SimpleAuthenticationInfo info = shiroFactory.info(shiroUser,user,super.getName());
        return info;
    }

    @Override
    public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
        HashedCredentialsMatcher md5Matcher = new HashedCredentialsMatcher();
        md5Matcher.setHashAlgorithmName(ShiroKit.hashAlgorithmName);
        md5Matcher.setHashIterations(ShiroKit.hashIterations);
        super.setCredentialsMatcher(md5Matcher);
    }
}
